package JUC.PC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author mubei
 * @date 2021/11/21
 * @description
 */
public class C {

    // a---b---c
    public static void main(String[] args) {
        Data2 data2 = new Data2();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    data2.printA();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A").start(); new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    data2.printB();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"B").start();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    data2.printC();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"C").start();

    }
}


class Data2{
    private int num = 1;   // num % 3 == 1 A 执行

    private Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void printA() throws InterruptedException {
        lock.lock();
        try{
            while(num%3 != 1){
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"AAAA");
            num++;
            condition2.signal();
        }finally {
            lock.unlock();
        }

    }

    public void printB() throws InterruptedException {
        lock.lock();
        try{
            while(num%3 != 2){
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName()+"BBBB");
            num++;
            condition3.signal();
        }finally {
            lock.unlock();
        }
    }

    public void printC() throws InterruptedException {
        lock.lock();
        try{
            while(num%3 != 0){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"CCCC");
            num++;
            condition1.signal();
        }finally {
            lock.unlock();
        }
    }

}
